import React, {useContext, useEffect, useState, useRef} from 'react';
import matericals from '../../component/material';
import CreatorContext from './creator-context';
import './index.less';

export default (props: any) => {
  const {compConfigs, setCompConfigs} = useContext(CreatorContext);
  const {bricksConfigs, dragComp, childrenNode} = compConfigs;
  // const [dropPreview, setDropPreview] = useState(false);
  const renderELems: any = useRef([]);
  const elemsPosition: any = useRef([]); // [{l, t, w, h, isChild}]
  const preView: any = useRef(null);
  // 移动时，要展示投影位置
  const dragOverHandler = (event: any) => {
    event.preventDefault();
    // setDropPreview(true);
    // console.log('dragOverHandler');
    preView.current.style.cssText = `width: 100%; display: block; left: 0; top: 0;`;
    // 根据鼠标位置 和 元素位置，设置出预览模块的位置和大小
    console.log('dragOverHandler', elemsPosition);
    // renderELems.current.
  }
  const dragLeaveHandler = (event: any) => {
    preView.current.style.cssText = `display: none;`;
    // setDropPreview(false);
    console.log('dragLeaveHandler');
  }
  const dropHandler = () => {
    console.log('dropHandler', dragComp);
  }
  useEffect(() => {
    renderELems.current.forEach((el: HTMLElement, index: Number) => {
      elemsPosition.current.push({
        h: el.offsetHeight, w: el.offsetWidth, l: el.offsetLeft, t: el.offsetTop, 
        isWrap: true, index
      });
    });
    if(dragComp){
      console.log(compConfigs);
    }
    console.log(compConfigs);
  }, [compConfigs]);
  renderELems.current = []; // 初始化这个数组，render后会重新填充
  elemsPosition.current = [];
  return <div className="splice-pancel-container">
    <div className="view" onDragLeave={dragLeaveHandler} onDragOver={dragOverHandler} onDrop={dropHandler}>
      {bricksConfigs.map((itemObj: any, index: number) => {
        const { displayName, demoProps } = itemObj;
        const Item = matericals[displayName];
        // 这里的ITEM是组建！不是原始DOM，“TMD”
        return (<div ref={(el) => { 
          if(el){renderELems.current = [...renderELems.current, el]; }}
        } key={index}><Item {...demoProps} /></div>);
      })}
      {/* <div ref={preView} className={`preview ${dropPreview ? '' : 'hide'}`}></div> */}
      <div ref={preView} className={`preview hide`}></div>
    </div>
  </div>
}
